package com.example.androidcomplete02.fragment;

import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.androidcomplete02.R;

public class PlanetListFragment extends ListFragment {
	String[] planets;
	int mLastIndex;
	boolean mMultiPane;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		planets = getResources().getStringArray(R.array.PLANET);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListAdapter(new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_activated_1, planets));
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		if (savedInstanceState != null) {
			mLastIndex = savedInstanceState.getInt("lastindex");
		}
		View descPanel = getActivity().findViewById(
				R.id.ch20_multipanewidth_descpanel);
		if (descPanel != null && descPanel.getVisibility() == View.VISIBLE) {
			mMultiPane = true;
			onListItemClick(getListView(), null, mLastIndex, 0);
		}
	}

	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("lastindex", mLastIndex);
	}

	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		mLastIndex = position;
		getListView().setItemChecked(position, true);
		if (mMultiPane) {
			FragmentManager fm = getFragmentManager();
			PlanetDescFragment df = (PlanetDescFragment) fm
					.findFragmentById(R.id.ch20_multipanewidth_descpanel);
			if (df == null || df.mNowIndex != position) {
				df = PlanetDescFragment.newInstance(position);
				fm.beginTransaction()
						.replace(R.id.ch20_multipanewidth_descpanel, df)
						.commit();
			}
		} else {
			Intent intent = new Intent(getActivity(), PlanetDescActivity.class);
			intent.putExtra("index", position);
			startActivity(intent);
		}
	}
}